package com.ttg.web.config;

import com.ttg.common.entities.UserTokenInfo;
import com.ttg.common.utils.UserUtil;
import com.ttg.web.utils.AccountDimTypeUtil;
import com.ttg.web.utils.AccountItemTypeUtil;
import com.ttg.web.utils.CostGradingUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Aspect
@Component
@Slf4j
public class ParamAspect {

    @Value("${autotask.ip:1}")
    private String allowIp;

    @Around(value = "execution(* com.ttg.web.task..*(..)) || " +
                    "execution(* com.ttg.web.controller..*(..)) ")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        log.info("--ParamAspect--");
        /*try {
            Boolean authority = false;
            String pubIpAddress = "";
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLoopbackAddress() && address.isSiteLocalAddress()) {
                        if (address.getHostAddress().equals(allowIp)){
                            log.info("---------------获取自动任务执行令牌成功---------------");
                            authority = true;
                        }
                    }
                }
            }
            if (!authority){
                log.error("非白名单服务器禁止执行自动任务");
                return null;
            }
        } catch (Exception e) {
            log.error("获取本机公网ip失败，取消执行");
            e.printStackTrace();
        }*/


        try{
            //todo 本地测试开启
            setDefaultUser();
            return point.proceed();
        }finally {
            //线程结束时，删除
            AccountItemTypeUtil.removeItemMap();
            AccountDimTypeUtil.removeDimMap();
            CostGradingUtil.removeDimMap();
        }

    }

    public void setDefaultUser(){
        if(UserUtil.getUser() == null){
            //设置默认用户信息
            UserTokenInfo user = new UserTokenInfo();
            user.setAdmId(860000102L);
            user.setOrgNo(860000000L);
            UserUtil.setUser(user);
        }
    }
}